<?php

namespace app\models;

use Yii;
use app\components\Wechat;
use app\components\Log;


/**
 * This is the model class for table "wx_js_ticket".
 *
 * @property integer $id
 * @property string $ticket
 * @property string $expiration_time
 */
class ApiTicket extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'wx_api_ticket';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['ticket', 'expiration_time'], 'string', 'max' => 255],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'ticket' => 'Ticket',
            'expiration_time' => 'Expiration Time',
        ];
    }

    public static function getapiticket()
    {
        $data = ApiTicket::find()->select('expiration_time, ticket')->orderBy('id DESC')->limit(1)->asArray()->one();
        if(isset($data) && $data['expiration_time'] > time()){
            return $data['ticket'];
        }else{
            $re = Wechat::get_api_ticket();
            Log::debug('api_ticket', $re);
            if($re['errmsg'] == "ok"){
                $model = new ApiTicket();
                $model->expiration_time = time()+7000;
                $model->ticket = $re['ticket'];
                $model->save(false);
                return $re['ticket'];
            }else{
                return $re;
            }
        }
    }

    // h5卡卷领取的签名算法
    public static function getsignature($card_id)
    {
        // 微信卡卷apiticket
        $api_ticket = self::getapiticket();
        // 时间戳
        $timestamp = time();
        // 用户的openid
        // $openid = Yii::$app->user->identity->openid;
        // 获取随机字符串
        $nonce_str = self::getNonceStr();

        // 字典排序
        $sign_array = [$card_id, $api_ticket, $timestamp, $nonce_str];
        asort($sign_array,SORT_STRING);

        $signa = '';
        foreach ($sign_array as $v) {
            $signa .= $v;
        }
        // 字符串进行sha1加密
        $signa = sha1($signa);

        $signastr = [
            'timestamp' => $timestamp,
            'nonce_str' => $nonce_str,
            'signature' => $signa,
        ];
        return $signastr;
    }

    //得到16位随机字符串
    private static function getNonceStr($length = 16) 
    {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }
}
